#!/usr/bin/python

import mosquitto
import time
import sys

if len(sys.argv)<>2:
    print("Argument required - ROOM")
    sys.exit(8)

def on_connect(mosq, rc):
    if rc == 0:
        print("Connected OK")
    else:
        print("Error Connecting")
        sleep(5)
        notifier.connect("KitchenPI.home")

def on_disconnect(mosq):
    print("Disconnected.")
    notifier.connect("KitchenPI.home")

def on_publish(mosq, mid):
    pass

notifier = mosquitto.Mosquitto("temperature-notify")
print("Created notifier")
notifier.on_connect = on_connect
notifier.on_disconnect = on_disconnect
notifier.on_publish = on_publish
print("Defined callbacks")
notifier.connect("KitchenPI.home")

lastTemp1="x"
lastTemp2="y"
temperature=""
while(lastTemp1!=temperature or lastTemp1!=lastTemp2):
    tfile = open("/sys/bus/w1/devices/28-00000539a84c/w1_slave") 
    text = tfile.read() 
    tfile.close() 
    lastTemp1=lastTemp2
    lastTemp2=temperature
    temperature = float(text.split("\n")[1].split(" ")[9][2:]) / 1000
    time.sleep(2)

notifier.publish("temp/"+sys.argv[1], str(temperature))
